package com.spsy.pay.service.impl;
import com.spsy.pay.domain.Pay;
import com.spsy.pay.order.WeiXinUtil;
import com.spsy.pay.service.IPayService;
import com.spsy.pay.service.PayApiService;
import com.spsy.pay.vo.PayResult;
import lombok.extern.slf4j.Slf4j;
import com.spsy.pay.order.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;

/**
 * 支付处理逻辑
 * @author: liuzhiping
 * @date: 2024/12/12 16:04
 **/
@Service
@Slf4j
public class PayApiServiceImpl implements PayApiService {

    @Autowired
    private IPayService iPayService;


    @Override
    public PayResult pay(String orderId) throws Exception {

        log.info("orderId:{}",orderId);

        //保存数据库

        Pay pay  = Pay.builder().
                notifyUrl(Constants.NOTIFY_URL)
                .channelId("bw")
                .payStatus(Long.valueOf(1))
                .payAmount(Long.valueOf(1))
                .asynUrl(Constants.NOTIFY_URL)
                .channelStatus(Long.valueOf(0))
                .channelName("八维产品")
                .merchandId(Constants.MCH_ID)
                .orderId(orderId)
                .paymentFee(Long.valueOf(0))
                .paymentJson("")
                .paymentStatus(Long.valueOf(0))
                .paymentMethodId("")
                .paymentTime(new Date())
                .privateKey("")
                .tradeType("微信")
                .merchandId("100001")
                .payAmount(Long.valueOf(1))
                .build();

        int count = this.iPayService.insertPay(pay);

        log.info("插入count:"+count);

        //二维码
        String codeUrl = WeiXinUtil.payOrder(orderId);
        log.info("二维码 codeUrl:{}",codeUrl);

        //判断二维码为空
        if(StringUtils.isBlank(codeUrl)){
            return  PayResult.builder().status(0).data("下单失败").build();
        }

        //修改数据库
        pay.setCodeUrl(codeUrl);
        //未支付且有二维码
        pay.setPayStatus(Long.valueOf(2));
        int updateCount = this.iPayService.updatePay(pay);

        log.info("修改数据库 updateCount:{}",updateCount);

        return PayResult.builder().data(codeUrl).status(1).build();

    }

    @Override
    public PayResult view(String orderId) throws Exception {

       Map<String,String> map  = WeiXinUtil.queryOrder(orderId);

       String returnCode = map.get("return_code");
       //成功的话
       if(returnCode.equals("SUCCESS")){
            int updateCount = this.iPayService.updatePayByOrderId(Pay.builder().payStatus(new Long(3)).orderId(orderId).build());

            log.info("修改成功 updateCount:{}",updateCount);
       }

        return PayResult.builder().status(1).msg("成功").build();
    }
}
